package de.hsb.ai.devil.ui.components;

import jade.core.AID;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.table.DefaultTableModel;

import de.hsb.ai.devil.agent.AgentManager;
import de.hsb.ai.devil.agent.DevilManagementAgent;

public class DevilTableModel extends DefaultTableModel implements DevilManagementAgent.EventHandler{
	
	private Vector rows = new Vector();
	private Vector<String> headerNames = new Vector<String>();
	
	public static final int AID_INDEX = 2;

	public DevilTableModel(){
		super();
		
		headerNames.add("Name");
		headerNames.add("Type");
		this.setDataVector(rows, headerNames);
	}
	
	public void addNewAgentToTable(DFAgentDescription agent){
		Vector newAgent = new Vector();
		newAgent.add(agent.getName().getLocalName());
		StringBuilder builder = new StringBuilder();
		Iterator<?> serviceIter = agent.getAllServices();
		while(serviceIter.hasNext()){
			builder.append(((ServiceDescription)serviceIter.next()).getName()).append(" ");
		}
		newAgent.add(builder.toString());
		newAgent.add(agent.getName());
		
		rows.add(newAgent);
		
		fireTableDataChanged();
	}
	
	private void deleteAgentFromTable(AID name) {
		for (int i = 0; i < rows.size(); i++) {
			if(name.equals(((Vector)rows.get(i)).get(AID_INDEX))){
				removeRow(i);
			}
		}
	}
	
	public AID getAID(int row){
		return (AID) getValueAt(row, AID_INDEX);
	}
	
	
//	@Override
//	public Class<?> getColumnClass(int columnIndex) {
//		return super.getColumnClass(columnIndex);
//	}
	
	@Override
	public boolean isCellEditable(int row, int column) {
		return false;
	}

	@Override
	public void handle(DFAgentDescription agent, Event e) {
		switch(e){
		case ADDED: 
			addNewAgentToTable(agent);
			break;
		case REMOVED:
			deleteAgentFromTable(agent.getName());
			break;
		}
	}
	
//    public Class getColumnClass(int column) {
//        Class returnValue;
//        if ((column >= 0) && (column < getColumnCount())) {
//          returnValue = getValueAt(0, column).getClass();
//        } else {
//          returnValue = Object.class;
//        }
//        return returnValue;
//      }
    public Class<?> getColumnClass(int column) {
        return getValueAt(0, column).getClass();
      }


}